// JS Bridge 等全局变量定义
var JSBridge = JSBridge || (JSBridge = {});

var responseCallbacks = {};
var messageHandlers = {};
var platform_iOS = false;

// 定义外部接口，供应用直接调用
let dolh5 = {
    getAuthCode: function (params) {
        callHandler("getAuthCode", params);
    },
    device: {
        getDeviceInfo: function (params) {
            callHandler("getDeviceInfo", params);
        },
        getAppInfo: function (params) {
            callHandler("getAppInfo", params);
        },
        getNetworkType: function (params) {
            callHandler("getNetworkType", params);
        },
    },
    date: {
        datePicker: function (params) {
            // 参数校验
            if (
                !paramCheck(
                    ["format", "defaultDate"],
                    ["string", "string"],
                    params
                )
            ) {
                return;
            }
            callHandler("datePicker", params);
        },
        timePicker: function (params) {
            if (
                !paramCheck(
                    ["format", "defaultTime"],
                    ["string", "string"],
                    params
                )
            ) {
                return;
            }
            callHandler("timePicker", params);
        },
        datetimePicker: function (params) {
            if (
                !paramCheck(
                    ["format", "defaultDatetime"],
                    ["string", "string"],
                    params
                )
            ) {
                return;
            }
            callHandler("datetimePicker", params);
        },
        chooseTime: function (params) {
            if (!paramCheck(["defaultTime"], ["number"], params)) {
                return;
            }
            callHandler("chooseTime", params);
        },
        chooseDay: function (params) {
            if (!paramCheck(["defaultDay"], ["number"], params)) {
                return;
            }
            callHandler("chooseDay", params);
        },
        chooseInterval: function (params) {
            if (
                !paramCheck(
                    ["defaultStart", "defaultEnd"],
                    ["number", "number"],
                    params
                )
            ) {
                return;
            }
            callHandler("chooseInterval", params);
        },
    },
    contact: {
        chooseDeptPerson: function (params) {
            if (
                !paramCheck(
                    [
                        "title",
                        "multiple",
                        "keywords",
                        "maxEmps",
                        "pickedEmpList",
                        "pickedDeptList",
                        "disabledEmpList",
                        "disabledDeptList",
                        "responseEmpOnly",
                    ],
                    [
                        "string",
                        "boolean",
                        "string",
                        "number",
                        "object",
                        "object",
                        "object",
                        "object",
                        "boolean",
                    ],
                    params
                )
            ) {
                return;
            }
            callHandler("chooseDeptPerson", params);
        },
        chooseDeptInfo: function (params) {
            if (
                !paramCheck(
                    [
                        "title",
                        "multiple",
                        "keywords",
                        "maxDepts",
                        "pickedDeptList",
                        "disabledDeptList",
                    ],
                    [
                        "string",
                        "boolean",
                        "string",
                        "number",
                        "object",
                        "object",
                    ],
                    params
                )
            ) {
                return;
            }
            callHandler("chooseDeptInfo", params);
        },
    },
    nav: {
        setTitle: function (params) {
            if (!paramCheck(["title"], ["string"], params)) {
                return;
            }
            callHandler("setTitle", params);
        },
        close: function (params) {
            callHandler("close", params);
        },
    },
    media: {
        chooseImage: function (params) {
            callHandler("chooseImage", params);
        },
        previewImage: function (params) {
            callHandler("previewImage", params);
        },
        uploadFile: function (params) {
            callHandler("uploadFile", params);
        },
        downloadFile: function (params) {
            callHandler("downloadFile", params);
        },
    },
    storage: {
        setItem: function (params) {
            // 设置本地缓存
            if (!paramCheck(["name", "value"], ["string", "string"], params)) {
                return;
            }

            let name = params.name;
            let value = params.value;

            const onSuccess = params["onSuccess"];
            const onFail = params["onFail"];

            try {
                localStorage.setItem(name, value);
                onSuccess({ value: value });
            } catch (error) {
                onFail();
            }
        },
        getItem: function (params) {
            // 根据 key 得到 value
            if (!paramCheck(["name"], ["string"], params)) {
                return;
            }

            let name = params.name;

            const onSuccess = params["onSuccess"];
            const onFail = params["onFail"];

            try {
                let value = localStorage.getItem(name);
                onSuccess({ value: value });
            } catch (error) {
                onFail();
            }
        },
        clearItem: function (params) {
            // 清楚所有的本地存储
            const onSuccess = params["onSuccess"];
            const onFail = params["onFail"];

            try {
                localStorage.clearItem();
                onSuccess();
            } catch (error) {
                onFail();
            }
        },
        removeItem: function (params) {
            // 删除某个 key
            if (!paramCheck(["name"], ["string"], params)) {
                return;
            }

            let name = params.name;

            const onSuccess = params["onSuccess"];
            const onFail = params["onFail"];

            try {
                localStorage.removeItem(name);
                onSuccess();
            } catch (error) {
                onFail();
            }
        },
    },
};

// 随机函数名称
function randomFuncString() {
    const length = 8;

    let str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    let result = "";

    for (let i = length; i > 0; --i) {
        result += str[Math.floor(Math.random() * str.length)];
    }

    return `f_${result}`;
}

// 参数校验
function paramCheck(names, types, params) {
    if (!params || typeof params !== "object") {
        return false;
    }

    let onFail = params.onFail;

    for (let i = 0; i < names.length; i++) {
        const name = names[i];
        const type = types[i];

        if (!params.hasOwnProperty(name) || typeof params[name] !== type) {
            if (!!onFail) {
                onFail({
                    code: 1000,
                    msg: "参数错误",
                });
            }

            return false;
        }
    }

    return true;
}

// 注册 callback
function registerCallback(inputParams) {
    const callbackId = randomFuncString();

    responseCallbacks[callbackId] = (function (id, onSuccess, onFail) {
        return function (callbackParams) {
            // 解析 JSON 对象
            const params =
                typeof callbackParams === "object"
                    ? callbackParams
                    : JSON.parse(callbackParams);

            // 得到状态
            const code = params.code;

            if (code === 0) {
                if (onSuccess) {
                    onSuccess(params.data);
                }
            } else {
                if (onFail) {
                    onFail(params);
                }
            }

            // 删除
            delete responseCallbacks[id];
        };
    })(callbackId, inputParams.onSuccess, inputParams.onFail);

    return {
        callbackName: `responseCallbacks.${callbackId}`,
        callbackFunc: responseCallbacks[callbackId],
    };
}

//本地是否实现
function syncPlatform_iOS(isIOS){
    platform_iOS = isIOS;
}

// callHandler 实现
function callHandler(name, params) {
    const { callbackName, callbackFunc } = registerCallback(params);
   
    if (platform_iOS){
        var ios_bridge = window.webkit.messageHandlers.JSBridge;
        if (!ios_bridge){
            callbackFunc({ code: 1001, msg: "iOS没有找到对应的本地方法" });
        }else{
            ios_bridge.postMessage({"name":name,"params":JSON.stringify(params),"callbackName":callbackName});
        }
    }else{
        if (
            !window.JSBridge ||
            !window.JSBridge.hasHandler ||
            !window.JSBridge.hasHandler(name)
        ) {
            callbackFunc({ code: 1001, msg: "Android没有找到对应的本地方法" });
        } else {
            window.JSBridge.callHandler(name, JSON.stringify(params), callbackName);
        }
    }
}
